<?php
/**
 *
 * @author yupoxiong<i@yupoxiong.com>
 */

declare (strict_types=1);

namespace app\api\controller;

use think\facade\Config;
use think\Request;
use think\response\Json;
use app\api\service\AuthService;
use app\api\exception\ApiServiceException;


class AppletController
{

    //小程序获取手机号码并登录
    public function login(Request $request,AuthService $service) :Json
    {
        try {
            $param = $request->param();
            if (!isset($param['code']) || empty($param['code'])) {
                throw new ApiServiceException('参数不足：code');
            }
            $applet_config  = Config::get('wechat.applet');
            $post_data      = ['code'=>$param['code']];//小程序传来的code值
            $access_token   = get_wechat_token($applet_config);
            $url            = 'https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token='.$access_token;

            $resp = request_post($url,$post_data);
            $resp = '{
                        "errcode":0,
                        "errmsg":"ok",
                        "phone_info": {
                            "phoneNumber":"16627022888",
                            "purePhoneNumber": "16627022888",
                            "countryCode": 86,
                            "watermark": {
                                "timestamp": 1637744274,
                                "appid": "xxxx"
                            }
                        }
                    }';

            $data = json_decode($resp,true);//对json数据解码
            if (!empty($data['errcode'])){
                throw new ApiServiceException($data['errmsg']);
            }
            $return_data = $service->appletLogin($data['phone_info']['purePhoneNumber']);

            $return_data['countryCode'] = $data['phone_info']['countryCode'];
            return api_success($return_data);

        } catch (ApiServiceException $e) {
            return api_error('小程序获取手机号码失败，参考信息：'.$e->getMessage());
        }
    }
}